/**
 * @file utils/apiCreator 支持get、post、upload三种API
 * @author zhangxinyue
 */

import request from './apiRequest';
import config from './config';

export default function createApi() {
  // 自动补上URL前缀
  const padPrefix = (url) => {
    return config.urlPrefix + url;
  };

  // 将查询条件转换成字符串拼接的形式
  const queryToString = (query) => {
    const encode = encodeURIComponent; // 把字符串作为 URI 组件进行编码。
    const str = Object.keys(query)
      .map((key) => {
        if (encode(query[key]) !== '') {
          return `${encode(key)}=${encode(query[key])}`;
        } else {
          return ``;
        }
      })
      .join('&');
    return str;
  };

  return {
    /**
     * @param {string} url API url
     * @param {Object} query 请求参数
     */
    get(url, query) {
      const finalUrl = padPrefix(url); // 添加前缀后的URL
      const queryString = queryToString(query); // 将查询条件从对象形式转换为字符串形式
      const timestamp = new Date().getTime(); // 时间戳，避免接口数据缓存

      const finalGetUrl = queryString ? `${finalUrl}?${queryString}&_=${timestamp}` : `${finalUrl}?_=${timestamp}`;
      const headers = {
        hToken: localStorage.getItem('antd-pro-token'),
        Authorization: localStorage.getItem('access_token'),
        Accept: '*/*', // 请求头用来告知（服务器）客户端可以处理的内容类型，这种内容类型用MIME类型来表示。
      };

      const ivUser = localStorage.getItem('antd-pro-userId');
      if (ivUser) {
        if (finalUrl.indexOf('evar/api') > -1) {
          // 所有请求evar接口的，请求头里加maat-user= EVAR_maat&PressureTest123!!
          headers['maat-user'] = 'EVAR_maat&PressureTest123!!';
        } else {
          headers['iv-user'] = ivUser;
        }
      }
      return request(finalGetUrl, {
        method: 'GET',
        headers,
      });
    },

    /**
     * @param {string} url API url
     * @param {Object} query 请求参数
     */
    post(url, query) {
      const finalUrl = padPrefix(url); // 添加前缀后的URL
      const headers = {
        hToken: localStorage.getItem('antd-pro-token'),
        Authorization: localStorage.getItem('access_token'),
        Accept: 'application/json',
        'Content-Type': 'application/json;charset=UTF-8', // body中的传参需为JSON格式的字符串
      };
      const ivUser = localStorage.getItem('antd-pro-userId');
      if (ivUser) {
        if (finalUrl.indexOf('evar/api') > -1) {
          // 所有请求evar接口的，请求头里加maat-user= EVAR_maat&PressureTest123!!
          headers['maat-user'] = 'EVAR_maat&PressureTest123!!';
        } else {
          headers['iv-user'] = ivUser;
        }
      }
      return request(finalUrl, {
        method: 'POST',
        headers,
        body: JSON.stringify(query),
      });
    },

    /**
     * @param {string} url API url
     * @param {Object} query 请求参数
     * @file {FormData} file 文件流
     */
    uploadFile(url, query, file) {
      const finalUrl = padPrefix(url); // 添加前缀后的URL
      const queryString = queryToString(query); // 将查询条件从对象形式转换为字符串形式
      const headers = {
        hToken: localStorage.getItem('antd-pro-token'),
        Authorization: localStorage.getItem('access_token'),
        Accept: 'application/json',
      };
      const ivUser = localStorage.getItem('antd-pro-userId');
      if (ivUser) {
        headers['iv-user'] = ivUser;
      }
      return request(`${finalUrl}${!queryString ? '' : `?${queryString}`}`, {
        method: 'POST',
        headers,
        body: file,
      });
    },
  };
}
